/**
 * 
 */
package com.tbdgroup.babycare.db;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

/**
 * @author wsf
 * 
 */
public class DBManager {

	private DBHelper helper;
	private SQLiteDatabase db;

	public DBManager(Context context) {
		helper = new DBHelper(context);
		db = helper.getWritableDatabase();
	}

	public void add(Event event) {
		db.beginTransaction();
		try {
			db.execSQL("INSERT INTO " + DBHelper.EVENT_TABLE
					+ " VALUES (null, ?, ?, ?)", new Object[] { event.type,
					event.start, event.end });
			db.setTransactionSuccessful();
		} finally {
			db.endTransaction();
		}
	}

	public int get(Event.E_TYPE type) {
		Cursor cur = db.rawQuery("SELECT * FROM " + DBHelper.EVENT_TABLE
				+ " WHERE type = ? and end = ?", new String[] { type.name(), "" });
		if (cur.moveToNext()) {
			return cur.getInt(cur.getColumnIndex("_id"));
		}
		return -1;
	}
	
	public void updateEnd(int id) {
		ContentValues cv = new ContentValues();  
        cv.put("end", new Date().getTime() + "");  
        db.update(DBHelper.EVENT_TABLE, cv, "_id = ?", new String[]{id + ""});  
	}
	
	public List<Event> getAllEvent() {
		List<Event> ret = new ArrayList<Event>();
		
		Cursor cur = db.rawQuery("SELECT * FROM " + DBHelper.EVENT_TABLE, new String[]{});
		while (cur.moveToNext()) {
			Event event = new Event();
			event._id = cur.getInt(cur.getColumnIndex("_id"));
			event.type = cur.getString(cur.getColumnIndex("type"));
			event.start = cur.getString(cur.getColumnIndex("start"));
			event.end = cur.getString(cur.getColumnIndex("end"));
			ret.add(event);
		}
		return ret;
	}

	/**
	 * close database
	 */
	public void closeDB() {
		db.close();
	}
}
